package com.rbmh.network.service.impl;

import com.rbmh.network.config.FtpClientConfig;
import com.rbmh.network.service.FtpService;
import com.rbmh.network.utils.ApacheFtpClient;
import com.rbmh.network.constant.FtpConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Base64;

/**
 * @author Administrator
 * @date 2021/11/19
 */
@Service
@Slf4j
@AllArgsConstructor
public class FtpServiceImpl implements FtpService {

    private final FtpClientConfig ftpClientConfig;

    @Override
    @Async
    public void pullFtpFiles(String dzzzdzs) {
        String[] dzzzdArr = dzzzdzs.split(",");
        if (ArrayUtils.isEmpty(dzzzdArr)) {
            return;
        }

        // 创建根路径
        File path = new File(FtpConstant.FTP_UPLOAD_PATH);
        if (!path.exists() || !path.isDirectory()) {
            log.info("根路径不存在");
            path.mkdirs();
        }

        // ftp连接
        ApacheFtpClient ftpClient;
        try {
            ftpClient = new ApacheFtpClient(ftpClientConfig.getHostname(), ftpClientConfig.getPort(), ftpClientConfig.getUserName(), ftpClientConfig.getPassword());
        } catch (IOException e) {
            ftpClient = null;
            log.error("ftp连接异常: {}", e.getMessage());
        }

        int i = 0;

        // ftp获取资源
        for (String ddzzdz : dzzzdArr) {

            // 校验文件是否存在
            File file = new File(ddzzdz);
            if(file.exists() && !file.isDirectory()){
                log.info("{}文件已存在", ddzzdz);
                continue;
            }

            ByteArrayOutputStream byteArrayOutputStream = null;
            FileOutputStream outputStream = null;
            try {
                // 初始化流
                byteArrayOutputStream = new ByteArrayOutputStream();
                outputStream = new FileOutputStream(file);

                // 使用文件输出流写入数据
                if (ftpClient != null && ftpClient.ftpClient.retrieveFile(ddzzdz, byteArrayOutputStream)) {
                    outputStream.write(byteArrayOutputStream.toByteArray());
                    i++;
                }
            } catch (Exception e) {
                log.info("ftp下拉文件出现异常");
                e.printStackTrace();
            } finally {
                if (byteArrayOutputStream != null) {
                    try {
                        byteArrayOutputStream.close();
                    } catch (IOException e) {
                        log.info("关闭流byteArrayOutputStream出现异常");
                        e.printStackTrace();
                    }
                }

                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        log.info("关闭流outputStream出现异常");
                        e.printStackTrace();
                    }
                }
            }
            if (i > 1000) {
                // ftp关闭
                if (ftpClient != null) {
                    ftpClient.close();
                }
                try {
                    ftpClient = new ApacheFtpClient(ftpClientConfig.getHostname(), ftpClientConfig.getPort(), ftpClientConfig.getUserName(), ftpClientConfig.getPassword());
                } catch (IOException e) {
                    ftpClient = null;
                    log.error("ftp连接异常: {}", e.getMessage());
                }
                i = 0;
            }
        }

        // ftp关闭
        if (ftpClient != null) {
            ftpClient.close();
        }
    }

    @Override
    public String getFtpFileBase64(String dzzzdz) {

        // 文件
        String fileBase64Str = "";

        // 校验文件是否存在
        File file = new File(dzzzdz);
        if(!file.exists()){
            return fileBase64Str;
        }

        // byte[]转base64
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(dzzzdz);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            fileBase64Str = Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (IOException e) {
            log.info("文件系统流出现异常");
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException ioe) {
                    log.info("关闭流fileInputStream出现异常");
                    ioe.printStackTrace();
                }
            }
        }

        return fileBase64Str;
    }

}
